<?php

// Linkroll administration ////////////////////////////////////////

if( !$PARAPARA || !$PARAPARA->is_admin() )
    return;

linkroll_topmenu();
echo "<h2>Linkroll administration</h2>\n";


$dbl = $PARAPARA->dblayer;

if( $do == 'form_action' ) {
    $form_action = '';
    if($_POST['del'] )
        $form_action = 'del';
    elseif($_POST['app'])
        $form_action = 'app';

    //--- delete links ----------------------------------------
    if($form_action == 'del') {
        $marked_links = array();
        foreach($_POST as $key => $value) {
            if( preg_match('/^[aw]link_(\d+)$/', $key, $matches ) ) {
                array_push( $marked_links, $matches[1]);
            }
        }

        if( sizeof( $marked_links) ) {

            $retval = $dbl->linkroll_delete_links( $marked_links );

            if($retval >= 0)
                padm_infostatus( "Deleted $retval link(s)" );
            else
                padm_warn("There was a DB error... wtf?" );
        }
        else {
            padm_infostatus("No links selected");
        }
    }


    // approve links -------------------------------------------------
    if($form_action == 'app') {
        $marked_links = array();
        foreach($_POST as $key => $value) {
            if( preg_match('/^wlink_(\d+)$/', $key, $matches ) ) {
                array_push( $marked_links, $matches[1]);
            }
        }

        if( sizeof( $marked_links) ) {

            $retval = $dbl->linkroll_approve_links( $marked_links );

            if($retval >= 0)
                padm_infostatus( "Approved $retval link(s)" );
            else
                padm_warn( "There was a DB error... wtf? :: $retval ::" );
        }
        else {
            padm_infostatus( "No links selected" );
        }
    }
    show_linkroll();
}

elseif( $do == 'enable' ) {

    $PARAPARA->config_set_save( 'LINKROLL', 'ON', 'true' );
    padm_infostatus( 'Enabled linkroll. The linkroll is now open for new links.' );

    show_linkroll();
}

elseif( $do == 'disable') {

    $PARAPARA->config_set_save( 'LINKROLL', 'ON', 'false' );

    padm_infostatus( 'Disabled linkroll. The linkroll is now closed for new links.');
    show_linkroll();
}

// User wants to edit link
elseif( $do == 'edit') {
    $link_id = $_GET['id'];
    if( is_numeric( $link_id ) ) {
        $link     = $dbl->get_linkroll_link( $link_id );
        if(!$link)
            padm_infostatus( "Link does not exist. Maybe somebody else has deleted it" );
        else
            edit_link( $link );
    }
    else
        padm_warn("No link id given");
}


// User wants to delete or save edited link
elseif( $do == 'save_link' ) {
    $link_id = $_POST['id'];
    if( is_numeric( $link_id ) ) {
        $link     = $dbl->get_linkroll_link( $link_id );
        if(!$link)
            padm_infostatus( "Link does not exist. Maybe somebody else has deleted it" );
        else {
            if($_POST['del'] ) {                
                $retval = $dbl->linkroll_delete_links( $link_id );
                if( $retval == 1 ) {
                    padm_infostatus("Link deleted");
                }
                elseif( $retval < 0 ) {
                    padm_infostatus("Database error. Noting deleted.");
                }
                elseif( $retval == 0 ) {
                    padm_infostatus("Link not found. Perhaps somebody else deleted it?");
                }
                
            }
            else {
                // FIXME !!!! check the attributes.... 
                $link->url         = $_POST['url'];
                $link->headline    = $_POST['headline'];
                $link->category_id = $_POST['cat_id'];
                $link->approved    = $_POST['approved'] ? 1 : 0;

                $status = $dbl->save_linkroll_link( $link );
                if( $status == 'ok' ) {
                    padm_infostatus( "Link saved" );
                }
                else {
                    padm_warn( "Could not save link : $status");
                }
            }
        }

    }
    else
        padm_warn("No link id given. That's strange.");

}

// view category list
elseif( $do == 'cats' ) {
    edit_linkroll_cats();
}

// view category list
elseif( $do == 'cat_edit' ) {
    $cat_id = $_GET['id'];

    if( !$cat_id )
        padm_warn("No category id given");
    else {
        $cat = $dbl->get_linkroll_category( $cat_id );
        if( $cat )
            edit_linkroll_cat( $cat );
        else
            padm_warn( "No category with this id" );
    }


}


elseif( $do == 'cat_save' ) {
    //FIXME: check the vars...

    $cat_name   = $_POST['name'];
    $cat_active = $_POST['active'] ? 1 : 0;

    if( $_POST['id'] ) {
        $cat_id = $_POST['id'];
        //update category
        $status = $dbl->save_linkroll_category( $cat_id, $cat_name, $cat_active );
        padm_infostatus( "Cat save ". $status . "::$cat_id::$cat_name" );
    }
    else {
        $status = $dbl->create_linkroll_category( $cat_name, $cat_active );
        padm_infostatus( "Cat create ". $status );
    }
}

else {
    show_linkroll();
}

return;



//// Helper functions //////////////////////////////////////////////////

function togglebox() {
    global $PARAPARA;

    $state = $PARAPARA->config_get('LINKROLL', 'ON');

    if($state == 'true') {
        echo 'The linkroll is enabled. <a href="?sec=link&do=disable">Disable linkroll</a>';
    }
    else {
        echo 'The linkroll is disabled. <a href="?sec=link&do=enable">Enable linkroll</a>';
    }
}


function list_linkroll() {
    global $PARAPARA;

    $dbl      = $PARAPARA->dblayer;
    $pager    = new Pager( $linkroll->link_count, 1, 100, '?sec=link');
    $linkroll = $dbl->get_linkroll_for_admin();

    if( $linkroll->link_count ) {

        if ($pager->page_count > 1)
            $pager->htmlize( array() );

        $buttons1 = 
            '<div class="padm_linkroll_buttons">' .
            '<button type="submit" class="padm_button" name="app" value="Approve">Approve</button>' .
            '<button type="submit" class="padm_button" name="del" value="Delete">Delete</button>' .
            "</div>\n";

        $buttons2 = 
            '<div class="padm_linkroll_buttons">' .
            '<button type="submit" class="padm_button" name="del" value="Delete">Delete</button>' .
            "</div>\n";


        echo "<h3>Links need approval</h3>\n";
        echo '<form action="?sec=link&do=form_action" method="POST">' . "\n";

        if( $linkroll->waiting_count ) {
            // list links waiting for approval
            echo "<table id=\"padm_linkroll_links_waiting\">\n";
            echo "<thead>\n";
            echo "<tr>",
                '<th>Date</th>',
                '<th>Category</th>',
                '<th>Link</th>',
                '<th>Submitter</th>',
                '<th>IP</th>',
                '<th>Edit</th>',
                '<th>Mark</th>',
                "</tr>\n";
            echo "</thead>\n";

            echo "<tbody>\n";
            foreach($linkroll->links as $link)
                if(!$link->approved) {
                    $catstring    = $linkroll->get_category_string( $link );
                    $sf_url       = htmlspecialchars( $link->url );
                    $sf_headline  = htmlspecialchars( $link->headline);
                    $sf_subby     = htmlspecialchars( $link->submitter );
                    $sf_category  = $catstring ? htmlspecialchars( $catstring ) : "UNKNOWN";
                    $sf_id        = htmlspecialchars( $link->id );
                    $sf_timestamp = $link->timestamp;
                    $sf_ip        = $link->ip;

                    echo "<tr>";
                    echo "<td class=\"timestamp\">",
                        $sf_timestamp,  "</td>";
                    echo "<td class=\"category\">",
                        $sf_category,  "</td>";
                    echo "<td class=\"link\">",
                        "<a href=\"$sf_url\">$sf_headline</a>",
                        "</td>";
                    echo "<td class=\"submitter\">",
                        $sf_subby, "</td>";
                    echo "<td class=\"ip\">",
                        $sf_ip, "</td>";
                    echo "<td class=\"edit\">",
                        "<a href=\"admin.php?sec=link&do=edit&id=$sf_id\">Edit</a>", "</td>";
                    echo "<td class=\"mark\">",
                        "<input name=\"wlink_$sf_id\" value=\"$sf_id\" type=\"checkbox\" />",
                        "</td>";
                    echo "</tr>\n";
                }
            echo "</tbody>\n";
            echo "</table>\n";
            echo $buttons1;
        }
        else {
            padm_info("No links waiting for approval");
        }

        echo "<h3>Approved Links</h3>\n";
        if( $linkroll->approved_count ) {
            // list approved links
            echo "<table id=\"padm_linkroll_links_approved\">";
            echo "<thead>\n";
            echo "<tr>",
                '<th>Date</th>',
                '<th>Category</th>',
                '<th>Link</th>',
                '<th>Submitter</th>',
                '<th>IP</th>',
                '<th>Edit</th>',
                '<th>Mark</th>',
                "</tr>\n";
            echo "</thead>\n";

            echo "<tbody>\n";
            foreach( $linkroll->links as $link)
                if( $link->approved ) {
                    $catstring    = $linkroll->get_category_string( $link );
                    $sf_url       = htmlspecialchars( $link->url );
                    $sf_headline  = htmlspecialchars( $link->headline);
                    $sf_subby     = htmlspecialchars( $link->submitter );
                    $sf_category  = $catstring ? htmlspecialchars( $catstring ) : "UNKNOWN";
                    $sf_id        = htmlspecialchars( $link->id );
                    $sf_timestamp = $link->timestamp;
                    $sf_ip        = $link->ip;

                    echo "<tr>";
                    echo "<td class=\"timestamp\">",
                        $sf_timestamp,  "</td>";
                    echo "<td class=\"category\">",
                        $sf_category,  "</td>";
                    echo "<td class=\"link\">",
                        "<a href=\"$sf_url\">$sf_headline</a>",
                        "</td>";
                    echo "<td class=\"submitter\">",
                        $sf_subby, "</td>";
                    echo "<td class=\"ip\">",
                        $sf_ip, "</td>";
                    echo "<td class=\"edit\">",
                        "<a href=\"admin.php?sec=link&do=edit&id=$sf_id\">Edit</a>", "</td>";
                    echo "<td class=\"mark\">",
                        "<input name=\"alink_$sf_id\" value=\"$sf_id\" type=\"checkbox\" />",
                        "</td>";
                    echo "</tr>\n";
                }
            echo "</tbody>\n";
            echo "</table>";
            echo $buttons2;
        }
        else {
            padm_info("No approved links in the linkroll");
        }

        echo "</form>";
    }
    else {
        padm_info("No links in the linkroll" );
    }
}


function show_linkroll() {
    echo "<div class='padm_linkroll' />";
    togglebox();
    list_linkroll();
    echo "</div>\n";
}

function linkroll_topmenu() {
    echo "<div class=\"padm_submenu\">",
        "<span class='item'><a href=\"admin.php?sec=link\">Link List</a></span>",
        "<span class='item'><a href=\"admin.php?sec=link&do=cats\">Categories</a></span>",
        "</div>";

}



function edit_link_cat_select( $categories, $chosen ) {
    if(!$chosen)
        $chosen = 1;

    echo "<select name=\"cat_id\">\n";
    foreach ($categories as $cat ) {
        if($chosen == $cat->id)
            $selected = " selected=\"selected\"";
        else
            $selected = '';
        echo "<option value=\"$cat->id\">", 
            htmlspecialchars( $cat->name ),
            "</option>\n";                
    }
    echo "</select>\n";
}


function edit_link( $link ) {
    global $PARAPARA;

    $dbl      = $PARAPARA->dblayer;

    if( !$link ) {
        padm_info("Link not found");
    }
    else {
        $categories  = $dbl->get_linkroll_categories_for_admin();
        $sf_url      = htmlspecialchars( $link->url );
        $sf_headline = htmlspecialchars( $link->headline );
        $sf_id       = htmlspecialchars( $link->id );

        echo "<h3>Edit link</h3>";

        echo '<form action="?sec=link&do=save_link" method="POST">';
        echo "<input type=\"hidden\" name=\"id\" value=\"$sf_id\" />\n";
        echo "<table id='padm_linkroll_edit_form'>\n";

        echo "<tr>\n";
        echo "<td class=\"label\">URL:</td>\n";
        echo "<td class=\"value\">",
            "<input name=\"url\" type=\"text\" value=\"$sf_url\"/>",
            "</td>\n";
        echo "</tr>\n";


        echo "<tr>\n";
        echo "<td class=\"label\">Headline:</td>\n";
        echo "<td class=\"value\">",
            "<input name=\"headline\" type=\"text\" value=\"$sf_headline\"/>",
            "</td>\n";
        echo "</tr>\n";

        echo "<tr>\n";
        echo "<td class=\"label\">Category:</td>\n";
        echo "<td class=\"value\">",
            edit_link_cat_select( $categories, $link->category_id ),
            "</td>\n";
        echo "</tr>\n";

        $approved_checked = $link->approved ? ' checked="checked"' : '';
        echo "<tr>\n";
        echo "<td class=\"label\">Approved:</td>\n";
        echo "<td class=\"value\">",
            "<input name=\"approved\" type=\"checkbox\" value=\"1\" $approved_checked/>",
            "</td>\n";
        echo "</tr>\n";

        echo "<tr>\n";
        echo "<td colspan=\"2\" class=\"buttons\">",
            '<button type="submit" class="padm_button" name="del" value="Delete">Delete</button>' .
            '<button type="submit" class="padm_button" name="save" value="Save">Save</button>' .
          "</td>\n";
        echo "</tr>\n";

        echo "</table>";
        echo "</form>\n";
    }
  
}


function edit_linkroll_cats() {
    global $PARAPARA;

    $dbl      = $PARAPARA->dblayer;
    $cats     = $dbl->get_linkroll_categories_for_admin();


    echo "<h3>Linkroll categories</h3>";
    echo "<table id=\"padm_linkroll_cat_list\">\n";
    echo "<thead>\n";
    echo "<tr>",
        '<th>Name</th>',
        '<th>State</th>',
        '<th>&nbsp;</th>',
        "</tr>\n";
    echo "</thead>\n";

    foreach( $cats as $cat ) {
        echo "<tr>\n";
        echo "<td class=\"name\">",
            htmlspecialchars( $cat->name ),"</td>\n";
        echo "<td class=\"active\">",
            $cat->active ? 'active' : 'disabled',
            "</td>\n";
      echo "<td class=\"edit\">",
          "<a href =\"admin.php?sec=link&do=cat_edit&id=$cat->id\">Edit</a>",
            "</td>\n";
  
        echo "</tr>\n";
    }

    echo "</table>";


    echo "<h3>Add new category</h3>";
    edit_linkroll_cateditor( null );
}


function edit_linkroll_cat( $cat) {
    echo "<h3>Edit category</h3>";
    edit_linkroll_cateditor( $cat );
}


function edit_linkroll_cateditor( $cat ) {
    global $PARAPARA;

    if( $cat ) {
        $sf_id     = $cat->id;
        $sf_name   = htmlspecialchars( $cat->name );
        $sf_active = $cat->active ? '1' : '0';
    }
    else {
        $sf_id      = '';
        $sf_name    = '';
        $sf_active  = '1';
    }

    $active_checked = $sf_active ? ' checked="checked"' : '';

    echo '<form action="?sec=link&do=cat_save" method="POST">';
    echo "<input name=\"id\" type=\"hidden\" value=\"$sf_id\"/>";
  
   echo "<table id=\"padm_linkroll_cat_form\">\n";
    echo "<tr>\n";
    echo "<td class=\"label\">Name:</td>\n";
    echo "<td class=\"value\">",
            "<input name=\"name\" type=\"text\" value=\"$sf_name\"/>",
            "</td>\n";
    echo "</tr>\n";


    $active_checked = $sf_active ? ' checked="checked"' : '';
    echo "<td class=\"label\">Active:</td>\n";
    echo "<td class=\"value\">",
        "<input name=\"active\" type=\"checkbox\" value=\"1\" $active_checked/>",
        "</td>\n";
    echo "</tr>\n";


    echo "<tr>\n";
    echo "<td class=\"buttons\" colspan=\"2\">",
        '<button type="submit" class="padm_button" name="save" value="Save">Save</button>' ,
        "</td>\n";
    echo "</tr>\n";
  
    echo "</table>";
    echo "</form>\n";

    

}


?>